<?php

namespace App\Http\Controllers\Frontend\V10\Repay;

use App\Http\Requests\Frontend\V10\Repay\RepayRequest;
use App\Jobs\RepayCommonJobQueue;
use App\Jobs\RepayJobQueue;
use App\Jobs\RepayMonthJobQueue;
use App\Models\RepayRecord;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\RepaySummary;
use App\Models\SettingChannel;
use App\Models\Traits\Repay;
use App\Models\UserBankCard;
use App\Models\UserGlobal;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RepayController extends Controller
{
    protected $user;
    public function __construct(Request $request)
    {
        $this->middleware('auth:api');
        $this->user = auth('api')->user();

    }

    protected function isOldRepay(Request $request){
        $route = $request->route();
        if(isset($route->action) && !empty($route->action)){
            $as = $route->action['as'];
            $summaryInfo = RepaySummary::getUserCurrentRepay($this->user->id);
            switch ($as){
                case 'repay.put_repay':
                    //todo 判断资方是否是农信,广大
                    $channel_type = RepaySummary::getLoanChannel($summaryInfo->id);
                    if(false == $channel_type){
                        $oldRepay = new OldRepayController();
                        $result = $oldRepay->setMoneyRepay($request->only(['repay_type','card_id']));
                        return $result;
                    }
                    break;
                default:
                    break;
            }
        }
        return 1;

    }

    /**
     * Description:查询当期的还款情况,具体的还款金额  要看三个接口的调用成功情况
     * Author:lijiafei
     */
    public function getCurrentRepay()
    {
        //获取用户的全局状态是哪个?
        $userGlobalStatus = UserGlobal::where('uid',$this->user->id)->value('global_status');
        $res = [];
        switch ($userGlobalStatus){
            case UserGlobal::STATUS_REPAY_INIT:
                //还款初始
                $res = $this->getRepayInit();
                break;
            case UserGlobal::STATUS_REPAY_ING:
                //还款中
                $res = $this->repayIng();
                $res['status'] = $userGlobalStatus;
                break;
            case UserGlobal::STATUS_REPAY_FAILURE:
                //还款失败,通过record表获取是哪个失败
                $repayInfo = RepaySummary::getRepayLastLog($this->user->id);
                $res['status'] = UserGlobal::STATUS_REPAY_FAILURE;
                $res['msg'] = $repayInfo->recordOne->failure_message;
                break;

            case UserGlobal::STATUS_REPAY_SUCCESS:
                //还款成功
                $res['status'] = UserGlobal::STATUS_REPAY_SUCCESS;
                $res['msg'] = '还款成功';
                break;
            case UserGlobal::STATUS_REPAY_OVER:
                //全部结清
            default:
                $res['msg'] = '请调用别的接口';
                break;
        }
        return success($res);

    }

    /**
     * Description:获取全部还款的金额(剩余本金,还清息费,总计)
     * Author:lijiafei
     * 剩余本金 = 未还记录的amount总计
     * 总计 = 剩余本金 + 公共接口的提前还清手续费 + 资方的利息,罚息,手续费
     * 息费 = 总计 - 剩余本金
     */
    public function getAllRepayMoney(){
        $summary = RepaySummary::select('id','period_count','period','loan_id','rate','amount')->where('uid',$this->user->id)->orderByDesc('id')->first();

        $is_channel = RepaySummary::getLoanChannel($summary->id);
        if(false == $is_channel){
            //todo 农信
            $money = RepaySummary::getOldRepayMoney($summary->id);
            return success($money);
        }

        //剩余本金
        $amount = RepayRecord::where('summary_id',$summary->id)->where('period','>=',$summary->period)->sum('amount');
        $amount = bcdiv($amount,100,2);

//        $moneyData = RepaySummary::getRepaymentPlan($summary->loan_id,$summary->id);

        //获取的是资方+公共的合计
        $info = Repay::repaymentMoney($summary->period,$summary->id);
        $all_money = bcadd($amount,$info,2);
        //总计
//        $all_money = bcadd(bcadd($all_money,$moneyData['lending_money'],2),$moneyData['fines_money'],2);
        //息费
        $lending_money = bcsub($all_money,$amount,2);
        $returnData['money'] = $amount;//还款本金
        $returnData['repay_amount'] = $all_money;//应还金额
        $returnData['lending_money'] = $lending_money;//利息费
        return success($returnData);

    }


    /**
     * 点击还款成功或者失败
     */
    public function confirmRepay(){

        $userGlobalStatus = UserGlobal::where('uid',$this->user->id)->value('global_status');
        $repayInfo = RepaySummary::getRepaySummaryLog($this->user->id);
        DB::beginTransaction();
        try{
            $updateData = array();
            if($userGlobalStatus == UserGlobal::STATUS_REPAY_SUCCESS){
                //判断是否还清
                if(isset($repayInfo->recordOne) && $repayInfo->recordOne){
                    //还有未还的记录
                    $updateData['global_status'] = UserGlobal::STATUS_REPAY_INIT;
                    UserGlobal::where('uid',$this->user->id)->update($updateData);
                }else{
                    $updateData['global_status'] = UserGlobal::STATUS_REPAY_OVER;
                    UserGlobal::where('uid',$this->user->id)->update($updateData);
                }
            }elseif($userGlobalStatus == UserGlobal::STATUS_REPAY_FAILURE){
                //把状态改为还款初始状态
                $updateData['global_status'] = UserGlobal::STATUS_REPAY_INIT;
                UserGlobal::where('uid',$this->user->id)->update($updateData);
                RepayRecord::where('id',$repayInfo->recordOne->id)->update(['status' => RepayRecord::STATUS_ONE]);
                //删除全部还清记录
                RepaySummary::deleteAllRepay($this->user->id);
            }
            DB::commit();
            return success($updateData);

        }catch (\Exception $e){
            Log::debug('还款:点击成功或失败按钮' . $e->getMessage());
            DB::rollBack();
            return failed('请求失败,请稍后重试');
        }

    }

    /**
     * Description:app点击全部还清,还当期
     * Author:lijiafei
     */
    public function setMoneyRepay(Request $request)
    {

        //todo 判断是否要走农信的逻辑  代码要优化
        $res = $this->isOldRepay($request);
        if($res != 1){
            if($res['flag'] === false){
                return failed($res['msg']);
            }elseif($res['flag'] === true){
                return success($res['msg']);
            }
        }

        // 1 还当期 2 全部还清
        $data['repay_type'] = $request->get('repay_type',1);
        $data['card_id'] = $request->get('card_id',0);
        $is_use_card = UserBankCard::select('id')->where('id',$data['card_id'])->where('uid',$this->user->id)->first();
        if(!$is_use_card){
            return failed('请选择正确银行卡');
        }
        if($data['repay_type'] == 1){

            $res = $this->repayCurrent($data['card_id']);
        }elseif($data['repay_type'] == 2){

            $res = $this->repayAll($data['card_id']);
        }else{
            return failed('请选择类型');
        }

        if($res['flag'] === false){
            return failed($res['msg']);
        }elseif($res['flag'] === true){
            return success($res['msg']);
        }
    }


    /**
     * Description:当期还
     * Author:lijiafei
     * @return
     */
    protected function repayCurrent($bank_cards_id){
        //获取当前应该还哪期的数据
        $repayInfo = RepaySummary::getRepaySummaryLog($this->user->id);
        $result = $this->validateCurrentRepay($repayInfo);
        if(!$result['flag']){
            return $result;
        }

        //判断当前银行卡是否有效
        $hold_agreement_num = UserBankCard::getHoldAgreementNumById($bank_cards_id,$repayInfo->id);
        if(!$hold_agreement_num){
            $returnData['flag'] = false;
            $returnData['msg'] = '请选择有效的银行卡';
            return $returnData;
        }
        //保存当前银行卡以及以后的所有银行卡信息
        $isSave = RepaySummary::saveBankInfo($bank_cards_id);
        if($isSave === false){
            $returnData['flag'] = false;
            $returnData['msg'] = '还款失败,请稍后重试';
            return $returnData;
        }

        $flag = RepaySummary::checkApi($repayInfo->recordOne->summary_id,$repayInfo->recordOne->uid);
        if(!$flag){
            $returnData['flag'] = false;
            $returnData['msg'] = '当日请求次数已达上限';
            return $returnData;
        }
        //调用队列
        $result = RepaySummary::setCurrentRepayJob($repayInfo->recordOne,RepayRecord::REPAY_TYPE_MANUAL);
        return $result;
    }

    /**
     * Description:全部结清方法
     * Author:lijiafei
     * @param $bank_cards_id int user_bank_card表的id
     * @return mixed
     */
    protected function repayAll($bank_cards_id){
        //获取当前应该还哪期
        $repayInfo = RepaySummary::getRepaySummaryLog($this->user->id);
        $result = $this->validateAllRepay($repayInfo);
        if(!$result['flag']){
            return $result;
        }

        //判断当前银行卡是否有效
        $hold_agreement_num = UserBankCard::getHoldAgreementNumById($bank_cards_id,$repayInfo->id);
        if(!$hold_agreement_num){
            $returnData['flag'] = false;
            $returnData['msg'] = '请选择有效的银行卡';
            return $returnData;
        }

        //获取全部还清的时候的记录 period = 0的记录
        $info = RepaySummary::getAllRepayLog($repayInfo->id,$repayInfo->uid);
        if(!$info){
            $returnData['flag'] = false;
            $returnData['msg'] = '提前结清失败';
            return $returnData;
        }

        $isSave = RepaySummary::saveBankInfo($bank_cards_id);
        if($isSave === false){
            $returnData['flag'] = false;
            $returnData['msg'] = '还款失败,请稍后重试';
            return $returnData;
        }

//        $flag = RepaySummary::checkApi($info->recordOne->summary_id,$info->recordOne->uid);
        try {
            $flag = RepaySummary::checkApi($info->recordOne->summary_id,$info->recordOne->uid);
        } catch (\Exception $e) {
            $flag = false;
            Log::debug('全部结清293行报错:', ['uid'=>$this->user->id,'info'=> $info,'error'=>$e->getMessage()]);
        }

        if(!$flag){
            $returnData['flag'] = false;
            $returnData['msg'] = '当日请求次数已达上限';
            return $returnData;
        }
        //调用队列
        $result = RepaySummary::setAllRepayJob($info->recordOne,RepayRecord::REPAY_TYPE_MANUAL);
        return $result;
    }

    /**
     * Description:检查是否超过最大请求次数
     * Author:lijiafei
     * @param $summary_id int repay_summary表id
     * @param $uid int 用户id
     * @return bool
     */
    protected function checkApiNumber($summary_id,$uid)
    {
        //判断是否达到当日最大次数
        $is_send_api = RepaySummary::checkApiNumber($summary_id,$uid,RepaySummary::COMMON_API);
        if(!$is_send_api){
            $returnData['flag'] = false;
            $returnData['msg'] = '当日请求次数已达上限';
            return $returnData;
        }

        //判断是否达到当日最大次数
        $is_send_api = RepaySummary::checkApiNumber($summary_id,$uid,RepaySummary::MONEY_API);
        if(!$is_send_api){
            $returnData['flag'] = false;
            $returnData['msg'] = '当日请求次数已达上限';
            return $returnData;
        }
        return $returnData['flag'] = true;
    }

    /**
     * Description:验证还当期
     * Author:lijiafei
     * @param $repayInfo
     * @return mixed
     */
    protected function validateCurrentRepay($repayInfo){
        if(!$repayInfo){
            $returnData['flag'] = false;
            $returnData['msg'] = '当前没有还款计划';
            return $returnData;
        }

        //当天存在已还款记录
        $is_pay = RepayRecord::where('summary_id',$repayInfo->id)->where('repay_date',Carbon::today()->toDateString())->first();
        if($is_pay){
            $returnData['flag'] = false;
            $returnData['msg'] = '当天已有还款记录,不能进行还款';
            return $returnData;
        }

        if($repayInfo->recordOne->status == RepayRecord::STATUS_TWO){
            //代表这条记录还在轮询中,不要还款
            $returnData['flag'] = false;
            $returnData['msg'] = '正在还款中,不能发起新的还款';
            return $returnData;
        }

        $isCurrentRepay = RepaySummary::isCurrentRepay($repayInfo->id);
        if(!$isCurrentRepay){
            $returnData['flag'] = false;
            $returnData['msg'] = '当前不能进行逐期还款';
            return $returnData;
        }
        $returnData['flag'] = true;
        $returnData['msg'] = '';
        return $returnData;
    }

    /**
     * 验证全部还清0
     */
    protected function validateAllRepay($repayInfo){
        if($repayInfo === false){
            $returnData['flag'] = false;
            $returnData['msg'] = '不能进行正常还款';
            return $returnData;
        }

        //当天存在已还款记录
        $is_pay = RepayRecord::where('summary_id',$repayInfo->id)->where('repay_date',Carbon::today()->toDateString())->first();
        if($is_pay){
            $returnData['flag'] = false;
            $returnData['msg'] = '当天已有还款记录,不能进行还款';
            return $returnData;
        }

        if($repayInfo->period  === $repayInfo->period_count){
            $returnData['flag'] = false;
            $returnData['msg'] = '最后一期不能进行提前结清';
            return $returnData;
        }
        if($repayInfo->period  === 1){
            $returnData['flag'] = false;
            $returnData['msg'] = '第一期不能进行提前结清';
            return $returnData;
        }
        if($repayInfo->recordOne->status == RepayRecord::STATUS_TWO){
            //代表这条记录还在轮询中,不要还款
            $returnData['flag'] = false;
            $returnData['msg'] = '正在还款中,不能发起新的还款';
            return $returnData;
        }
        $day = count_days(Carbon::now()->toDateString(),$repayInfo->recordOne->normal_date);
        if($day > 0){
            $returnData['flag'] = false;
            $returnData['msg'] = '逾期不能进行提前结清';
            return $returnData;
        }
        //判断是否可以全部还清
        $isAllRepay = RepaySummary::isAllRepay($repayInfo->recordOne);
        if(!$isAllRepay){
            $returnData['flag'] = false;
            $returnData['msg'] = '当前状态不能进行提前结清';
            return $returnData;
        }

        $returnData['flag'] = true;
        $returnData['msg'] = '';
        return $returnData;
    }

    protected function getRepayInit(){
        $returnData = array();
        $repayInfo = RepaySummary::getRepayLastLog($this->user->id);
        if(empty($repayInfo)){
            Log::debug('416行报错:', ['uid'=>$this->user->id,'info'=>$repayInfo]);
            return ['status'=>UserGlobal::STATUS_REPAY_FAILURE,'msg'=>'未知错误,请稍后再试'];
        }
        $returnData['summary_id'] = $repayInfo->id;//repay_summary表的id
        $returnData['amount'] = $repayInfo->amount;//借款金额
        $returnData['period'] = $repayInfo->recordOne->period;//当前期数
        $returnData['period_count'] = $repayInfo->period_count;//总共的期数
        $returnData['normal_date'] = $repayInfo->recordOne->normal_date;//正常还款日期
        $returnData['bank_cards_info'] = UserBankCard::getCardInfoByBankCardId($repayInfo->recordOne->bank_cards_id);//银行卡号
        $returnData['overdue_day'] = 0;

        $returnData['is_show_repay'] = 1; //全部还清按钮是否可点击
        $returnData['is_show_current_repay'] = 1; //逐期还款的按钮是否可点击
        //判断是否是还当期还是全部还清
        if($repayInfo->recordOne->pay_off == RepayRecord::PAY_OFF_ONE){
            $this->currentTotal($repayInfo,$returnData);//点击全部还清 可能有问题
        }elseif($repayInfo->recordOne->pay_off == RepayRecord::PAY_OFF_TWO){
            $this->allRepayTotal($repayInfo,$returnData);
        }
        if($returnData['normal_date']){
            $normal_date = explode('-',$returnData['normal_date']);
            $returnData['normal_date'] = implode('/',$normal_date);
        }
        $returnData['money'] = $repayInfo->recordOne->amount;//本金 (页面显示的利息  = 应还金额 - 本金)
        return $returnData;

    }

    /**
     * Description:还款中
     * Author:lijiafei
     */
    protected function repayIng(){
        $repayInfo = RepaySummary::getRepayLastLog($this->user->id);
        $returnData['bank_cards_info'] = UserBankCard::getCardInfoByBankCardId($repayInfo->recordOne->bank_cards_id);//银行卡号;
        $returnData['normal_date'] = $repayInfo->recordOne->normal_date;
        $returnData['overdue_day'] = 0;
        if($repayInfo->recordOne->pay_off == RepayRecord::PAY_OFF_ONE){
            $this->currentTotal($repayInfo,$returnData);
        }elseif($repayInfo->recordOne->pay_off == RepayRecord::PAY_OFF_TWO){
            $this->allRepayTotal($repayInfo,$returnData);
        }
        if($returnData['normal_date']){
            $normal_date = explode('-',$returnData['normal_date']);
            $returnData['normal_date'] = implode('/',$normal_date);
        }
        return $returnData;
    }

    /**
     * 获取逐期还款的总金额
     */
    protected function currentTotal($repayInfo,&$returnData){
        /*
        * 本期应还
        * record的本金
        * month的月保费
        * common的利息,管理费,罚息
        * money利息,手续费,罚息
        */
        $total = bcadd(bcadd(bcadd(bcadd(bcadd($repayInfo->recordOne->amount,$repayInfo->recordOne->month->amount,2),$repayInfo->recordOne->common->lending_money,2),$repayInfo->recordOne->common->manage_money,2),$repayInfo->recordOne->money->lending_money,2),$repayInfo->recordOne->money->repayment_money,2);

        if($repayInfo->period == 1 || $repayInfo->period  == $repayInfo->period_count){
            $returnData['is_show_repay'] = 0;
            $returnData['is_show_current_repay'] = 1;
        }
        //判断是否过期
        $count_day = count_days(Carbon::now()->toDateString(),$repayInfo->recordOne->normal_date);
        if($count_day > 0){

            $returnData['is_show_repay'] = 0;
            $returnData['is_show_current_repay'] = 1;

            $fines_rate = $repayInfo->rate['fines_rate'];
            //计算公共平台的罚息
            $fines_money = RepaySummary::getFines($repayInfo->recordOne->normal_date,$fines_rate,$repayInfo->amount,$repayInfo->recordOne->common->id);
            //计算资方平台的罚息
            $common_fines_money = $fines_money['common_fines_money'];
            $money_fines_money = $fines_money['money_fines_money'];
            $total = bcadd(bcadd($total,$common_fines_money,2),$money_fines_money,2);
        }
        //如果还了资方的,就不能提前结清了
        if(($repayInfo->recordOne->month->status == RepayRecordMonth::STATUS_FOUR && $repayInfo->recordOne->month->amount > 0)
            || $repayInfo->recordOne->money->status == RepayRecordMoney::STATUS_FOUR){
            $returnData['is_show_repay'] = 0;
            $returnData['is_show_current_repay'] = 1;
        }

        $returnData['overdue_day'] = $count_day > 0 ? $count_day : 0;//逾期天数
        $returnData['repay_amount'] = $total;
    }

    /**
     * 获取全部还清的总金额
     */
    protected function allRepayTotal($repayInfo,&$returnData){
        /*
         * record的本金
         * month的月保费
         * common的提前还清手续费
         * money利息,手续费,罚息
         */
        $total = bcadd(bcadd($repayInfo->recordOne->amount,$repayInfo->recordOne->month->amount,2),$repayInfo->recordOne->common->repayment_money,2);

        $returnData['is_show_repay'] = 1;
        $returnData['is_show_current_repay'] = 0;
        //todo 农信
        $is_channel = RepaySummary::getLoanChannel($repayInfo->id);
        if(false == $is_channel){
            $total = RepaySummary::getOldRepayMoney($repayInfo->recordOne->summary_id);
            $total = $total['repay_amount'];
        }else{
            //判断是否过期
            $moneyData = RepaySummary::getRepaymentPlan($repayInfo->loan_id,$repayInfo->id);
            $total = bcadd(bcadd(bcadd($total,$moneyData['lending_money'],2),$moneyData['fines_money'],2),$moneyData['repayment_money'],2);
        }


        //更改期数问题
        $period = RepayRecord::where('summary_id',$repayInfo->id)->where('pay_off',RepayRecord::PAY_OFF_ONE)->where('status','<>',RepayRecord::STATUS_FOUR)->orderBy('period','asc')->value('period');
        $returnData['period'] = $period;//期数应该是应还的哪一期,不应该是0
        $returnData['repay_amount'] = $total;
    }

    /**
     * Description: 用户历史借款记录
     * Author: Gxs
     * @param RepayRequest $request
     * @return mixed
     */
    public function history(RepayRequest $request)
    {
        $params = $request->all();
        $page_size = $request->get('page_size', 0);
        $params['uid'] = auth('api')->user()->getAuthIdentifier();
        $result = RepaySummary::getFrontHistoryList($params, $page_size);
        if (!empty($result['list'])) {
            $result['list'] = RepaySummary::parseHistoryList($result['list']);
        }
        return respond($result);
    }

    /**
     * Description: 借款记录 && 还款计划表
     * Author: Gxs
     * @param RepayRequest $request
     * @return mixed
     */
    public function index(RepayRequest $request)
    {
        //根据summary_id 获取列表
        $params = $this->extractInputFromRules($request,$request->rules());
        $summary_id = $params['summary_id'];
        $record_list = [];
        $plan_list = [];
        $summary_model = RepaySummary::where('id', $summary_id)->select([
            'id', 'period_count', 'loan_request_id'
        ])->first();
        if (!empty($summary_model)) {
            $result = RepaySummary::getFrontRepayList($summary_model); //获取用户最新借款记录
            $record_list = $result['record_list'];
            $plan_list = $result['repay_plan'];
        }
        $channel = '';
        if (isset($summary_model->relationUserLoanRequests->channel))
            $channel = $summary_model->relationUserLoanRequests->channel;
        $is_show_plan = SettingChannel::isShowPlan($channel); // 0 不显示 1 显示
        return respond([
            'record_list' => $record_list,
            'is_show_plan' => $is_show_plan,
            'plan_list' => $plan_list,
        ]);
    }



}
